#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import warnings 
import os 
import json
import openpyxl
import pandas as pd
import requests
from bs4 import BeautifulSoup
from openpyxl.utils.dataframe import dataframe_to_rows
import time

# ========================= ==============================================
xueqiuheaders = {
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0',
    'Content-Encoding': 'gzip',
    'Content-Type': 'text/html; charset=GBK',
    'authority':'stock.xueqiu.com',
    'sec-ch-ua':'" Not A;Brand";v="99", "Chromium";v="92", "Opera";v="78"',
    'upgrade-insecure-requests':	'1',
    'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site':'none',
    'sec-fetch-mode':'navigate',
    'sec-fetch-dest':'document',
    'accept-encoding':'gzip, deflate, br',
    'accept-language':'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cookie': 'xq_a_token=b02adfc63102d5b06db993fb320f0a7524962682; xqat=b02adfc63102d5b06db993fb320f0a7524962682; xq_r_token=7d049aff96056cd9fe153b20d88ded89ca04bb41; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTYyNzY5OTgxNCwiY3RtIjoxNjI2MzQwNzQ3ODE0LCJjaWQiOiJkOWQwbjRBWnVwIn0.ChwG6T5Cgl_TvgKsKjURZQVL0M471VH8kksp3hmPFeAmqWSd3O_nFYc285RiK4ivg-98q8-J8O4LbaAr6vc_HcW3R8vIzYQKDx8S-hTTo45JaEjNiudPlAhNpZNsU6jpNIifK_PccHN8rdI50G3AQz6gdIHfZlbP61CyLC_gw9tgmc8KqSKmZQxCU7GKTrtSXyU-pk3FVLPAWgQepJnm_Z3VB6nlJcdCFyU8QBAQD7eEsVLZRZl6JAaPfj6T6gRwZNQ9i7GE5X3HKmLYn3hoYoLV5emwuj2VwHE7XeLW7yNee8XfPI97K_e8-qKyZmDhxvDa2OB7r7vLnwexvO8LCQ; u=801626340773072; device_id=d32693509cfd60c70e140d9b19360c93'
}
sinaheaders = {
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0',
    'Accept-Encoding': 'gzip, deflate',
    'upgrade-insecure-requests':	'1',
    'Accept-Language':'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Content-Type': 'text/html; charset=GBK',
    'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
}

def update_session(headers):
    # 这里模拟一下请求头，头文件是从浏览器里面抓到的，否则服务会回复403错误，（其实就是服务器做的简单防爬虫检测）
    session.headers.clear()
    session.headers.update(headers)

session = requests.session()

def get_json_by_url(page_url):
    return get_page_by_url(page_url, True)

def get_text_by_url(page_url):
    return get_page_by_url(page_url, False)

def get_page_by_url(page_url, isJson):
    strtime = time.strftime("%m-%d", time.localtime())
    #print("get_page_by_url:" + strtime + " " + page_url)

    try:
        res = session.get(page_url, timeout=(30, 120))
        if res.status_code == 200:
            if(isJson):
                info = res.json()
            else:
                info = res.text
            #print("res:"+str(info))

            return info
    except Exception as e:
        print("error:" + str(e))
    return None

# ========================= ==============================================
stocks = {
    'sz399006':'创业指数',
    'sh000001':'上证指数',
    'sz000852':'石化机械',
    'sz300677':'英科医疗',
    'sz002127':'南极电商',
    'sh600435':'北方导航',
    'sz300783':'三只松鼠',
    'sz000878':'云南铜业',
    'sh600362':'江西铜业',
    'sh601106':'中国一重',
    'sh605090':'九丰能源',
    'sh600794':'保税科技',
    'sh603001':'奥康国际',
    'sh600903':'贵州燃气',
    'sz300253':'卫宁健康',
    'sz300141':'和顺电气',
    'sh688399':'硕士生物',
    'sh601318':'中国平安',
}

def xueqiu(url):
    update_session(xueqiuheaders)
    info = get_json_by_url(url)
    if info == "":
        return
    #print("data:"+str(info['data']))
    data = info['data']
    for value in data:
        #print(str(stocks[value['symbol'].lower()]) + "   " + str(value['current']) +"    " + str(value['percent']) +"%   " + str(value['high']) +"    " + str(value['open']))
    
        if value['percent'] >0 :
            print('%-7s %-7s \033[1;31m %-7s \033[0m %-8s %-8s' % (str(stocks[value['symbol'].lower()]), str(value['current']), str(value['percent']) +"%", str(value['turnover_rate']) +"%", str(value['open'])))
        else :
            print('%-7s %-7s \033[1;32m %-7s \033[0m %-8s %-8s' % (str(stocks[value['symbol'].lower()]), str(value['current']), str(value['percent']) +"%", str(value['turnover_rate']) +"%", str(value['open'])))
    
def sina(url):
    update_session(sinaheaders)
    info = get_text_by_url(url)
    if info == "":
        return
    data = info.split(';')
    for val in data:
        ss = val.split('=')
        if(len(ss)<2):
            continue
        item = ss[1]
        value = item[1:(len(item)-1)].split(',')
        #print("rest:"+str(value))
        #['秋田微', '51.200', '51.250', '53.110', '53.530', '51.110', '53.100', '53.110', '1626599', '85410471.030', '200', '53.100', '200', '53.090', '1800', '53.080', '100', '53.070', '1000', '53.010', '800', '53.110', '2700', '53.120', '1200', '53.140', '1100', '53.180', '552', '53.200', '2021-09-17', '15:35:00', '00', 'D|0|0.000']
        #名字,开盘价,昨天收盘价,当前价,最高价,最低价,买一,卖一,成交量,金额,买一数,买一报价,买二数,买二价,买三数,买三价,买四数,买四价,买五数,买五价.卖一数,卖一价,卖二数,卖二价,卖三数,卖三价,卖四数,卖四价,卖五数,卖五价.
        #print(str(value[0]) + "   " + str(value[3]) + "    " + str(value[2]) +"%           " + str(value[3]) +"    " + str(value[4]))
        percent = (float(value[3])-float(value[2])) /float(value[2])
        if percent >0 :
            print('%-7s %-7s \033[1;31m %-7.5s \033[0m %s' % (str(value[0]), str(value[3]), str(percent*100),"%"))
        else :
            print('%-7s %-7s \033[1;32m %-7.5s \033[0m %s' % (str(value[0]), str(value[3]), str(percent*100),"%"))

def tencent(url):
    update_session(sinaheaders)
    info = get_text_by_url(url)
    if info == "":
        return
    data = info.split(';')
    for val in data:
        ss = val.split('=')
        if(len(ss)<2):
            continue
        item = ss[1]
        value = item[1:(len(item)-1)].split('~')
        #print("rest:"+str(value))
        #v_sz300939="51~秋田微~300939~53.11~51.25~51.20~16266~8653~7613~53.10~2~53.09~2~53.08~18~53.07~1~53.01~10~53.11~8~53.12~27~53.14~12~53.18~11~53.20~6~~20210917161403~1.86~3.63~53.53~51.11~53.11/16266/85410471~16266~8541~8.13~49.82~~53.53~51.11~4.72~10.62~42.49~3.86~61.50~41.00~1.67~-31~52.51~57.75~50.98~~~0.74~8541.0471~0.0000~0~ AR~GP-A-CYB~42.85~1.03~0.94~7.74~6.36~145.50~47.60~6.37~10.30~-6.76~20000000~80000000~-31.96~42.85~20000000";
        #['51', '秋田微', '300939', '53.11', '51.25', '51.20', '16266', '8653', '7613', '53.10', '2', '53.09', '2', '53.08', '18', '53.07', '1', '53.01', '10', '53.11', '8', '53.12', '27', '53.14', '12', '53.18', '11', '53.20', '6', '', '20210917161403', '1.86', '3.63', '53.53', '51.11', '53.11/16266/85410471', '16266', '8541', '8.13', '49.82', '', '53.53', '51.11', '4.72', '10.62', '42.49', '3.86', '61.50', '41.00', '1.67', '-31', '52.51', '57.75', '50.98', '', '', '0.74', '8541.0471', '0.0000', '0', ' AR', 'GP-A-CYB', '42.85', '1.03', '0.94', '7.74', '6.36', '145.50', '47.60', '6.37', '10.30', '-6.76', '20000000', '80000000', '-31.96', '42.85', '20000000']
        #开盘价,昨天收盘价,当前价,最高价,最低价,买一,卖一,成交量,金额,买一数,买一报价,买二数,买二价,买三数,买三价,买四数,买四价,买五数,买五价.卖一数,卖一价,卖二数,卖二价,卖三数,卖三价,卖四数,卖四价,卖五数,卖五价.
        #print(str(value[1]) + "   " + str(value[3]) +"    " + str(value[32]) +"%   " + str(value[37]) +"    " + str(value[4]) + "    " + str(value[7]) + "    " + str(value[8]))
        if float(value[32]) >0 :
            print('%-7s %-7s \033[1;31m %-7s \033[0m %-8s %-8s \033[1;31m %-8s \033[0m %-8s' % (str(value[1]), str(value[3]), str(value[32]) +"%", str(value[38]) +"%", str(value[4]), str(value[7]), str(value[8])))
        else :
            print('%-7s %-7s \033[1;32m %-7s \033[0m %-8s %-8s \033[1;31m %-8s \033[0m %-8s' % (str(value[1]), str(value[3]), str(value[32]) +"%", str(value[38]) +"%", str(value[4]), str(value[7]), str(value[8])))

def getSymbol(isUpper) :
    stockList = ""
    for stock in stocks:
        if(isUpper) :
            stockList = stockList + "," + stock.upper()
        else :
            stockList = stockList + "," + stock.lower()

    return stockList

if __name__ == '__main__':
    #symbol="SZ300939,SH603533"
    xueqiu_url="https://stock.xueqiu.com/v5/stock/realtime/quotec.json?symbol=" + getSymbol(True)
    sina_url="http://hq.sinajs.cn/list=" + getSymbol(False)
    #http://image.sinajs.cn/newchart/daily/n/sh601006.gif 日k图
    #http://image.sinajs.cn/newchart/min/n/sh000001.gif 分时图
    tencent_url="http://qt.gtimg.cn/q=" + getSymbol(False)

    print("  名字      现价     涨幅     换手   均价/昨收    外盘     内盘")
    while True:
        #sina(sina_url)
        #xueqiu(xueqiu_url)
        tencent(tencent_url)
        time.sleep(4)







